package cadc.daos;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import cadc.models.Ping;

public class PingDao extends JdbcDaoSupport {
	public Ping getPing(int groupId, int pingId) {
		String sql = "select * from pings where groupId="+groupId+" and pingId="+pingId;
		List<Ping> items = super.getJdbcTemplate().query(sql, new PingRowMapper());
		if(items.isEmpty()||items.size()==0){  
			   return null;  
		}  
		return items.get(0);
	}

	public boolean addPing(long l, long pingId) {
		String sql = "insert into pings (groupId, pingId) values (?, ?)";
		return super.getJdbcTemplate().update(sql, l, pingId)>0;
	}

	public boolean updatePing(String columnName, String columnValue, int groupId, int pingId) {
		String sql = "update pings set "+columnName+"=? where groupId=? and pingId=?";
		return super.getJdbcTemplate().update(sql, columnValue, groupId, pingId)>0;
	}

	public List<Ping> getPingListOfGroup(int groupId) {
		String sql = "select * from pings where groupId="+groupId;
		return super.getJdbcTemplate().query(sql, new PingRowMapper());
	}


	public List<Ping> getPingListOfPing(int pingId) {
		String sql = "select * from pings where pingId="+pingId;
		return super.getJdbcTemplate().query(sql, new PingRowMapper());
	}

	class PingRowMapper implements RowMapper<Ping>{

		@Override
		public Ping mapRow(ResultSet rs, int rowNum) throws SQLException {
			Ping ping = new Ping();
			int[] pings = new int[6];
			int fen=0;
			for(int i=0; i<6; i++){
				pings[i] = rs.getInt("mark"+i);
				fen+=pings[i];
			}
			ping.setPings(pings);
			ping.setFen(fen);
			ping.setPingId(rs.getInt("pingId"));
			ping.setNum(rs.getInt("num"));
			ping.setPingyu(rs.getString("pingyu"));
			ping.setAddable(rs.getBoolean("addable"));
			ping.setPassed(rs.getBoolean("passed"));
			return ping;
		}
		
	}
}
